const express = require("express")
const router = express.Router()
const db = require("../../Database/index.js")
const fs = require("fs")
const path = require("path")
//检查登录状态
router.get("/check_login_status", (request, response) => {
    db.query("select * from users where username = ?", request.user.username, (err, result) => {
        if (err) return console.log(err.message)
        response.send({code: 200, message: "欢迎使用", userInfo: result[0]})
    })
})
//修改用户信息
router.post("/change_user_info", async (request, response) => {
    const data = await new Promise( (resolve, reject) => {
        request.on("data", (data) => {
            if (JSON.parse(data.toString())) resolve(JSON.parse(data.toString()))
        })
    })
    const flag = await new Promise( (resolve, reject) => {
        db.query("UPDATE users SET name = ?, age = ?, birthday = ?, text = ? where username = ?", [data.name, data.age, data.birthday, data.text, request.user.username], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) {
                resolve(true)
            }
        })
    })
    if (flag) {
        db.query("select * from users where id = ?", request.user.id, (err, result) => {
            if (err) return console.log(err.message)
            response.send({code: 200, message: "修改成功", userInfo: result[0]})
        })
    }
})
//修改头像
router.post("/upload_picture", async (request, response) => {
    new Promise( (resolve, reject) => {
        db.query("select * from users where id = ?", request.user.id, (err, result) => {
            if (err) return console.log(err.message)
            if (!result[0].pic.includes("default.jpg")) {
                fs.unlink(path.join(__dirname, "../../public/images/", result[0].pic.split("/images/")[1]), (err) => {
                    if (err) return console.log(err.message)
                })
            }
        })
    })
    const url = await new Promise( (resolve, reject) => {
        if (request.files.length > 0) {
            const fileName = new Date().valueOf() + request.files[0].originalname
            const url = `http://127.0.0.1:8080/public/images/${fileName}`
            fs.writeFile(path.join(__dirname, "../../public/images/", fileName), request.files[0].buffer, (err) => {

                if (err) return console.log(err.message)
                else resolve(url)
            })
        }
    })
    if (url) {
        db.query("UPDATE users set pic = ? where id = ?", [url, request.user.id], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) response.send({code: 200, message: "上传成功", url})
        })
    }
})

//用户上传视频
router.post("/upload_video",  async (request, response) =>  {
    const fileName = new Date().valueOf() + request.files[0].originalname
    const url = await new Promise( (resolve, reject) => {
        fs.writeFile(path.join(__dirname, "../../public/videos/", fileName), request.files[0].buffer, (err) => {
            if (err) return console.log(err.message)
            resolve(`http://127.0.0.1:8080/public/videos/${fileName}`)
        })
    })
    if (url) {
        db.query("insert into videos (like_count, tags, content, watch_count, title, url, time, username) values (?,?,?,?,?,?,?,?)", [
            0,
            JSON.stringify( request.body.tags),
            JSON.stringify([]),
            0,
            request.body.title,
            url,
            getTime(),
            request.user.username
        ], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) {
                response.send({code: 200, message: "上传成功", url})
            }
        })
    }
})


//注销账号
router.get("/logout", async (request, response) => {
    const {id: uid} = request.user
    //删除头像
    const delete_img = await new Promise( (resolve, reject) => {
        db.query("select * from users where id = ?", uid, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length === 1 && (!result[0].pic.includes("default"))) {
                const path_img = path.join(__dirname, "../../", result[0].pic.split("8080/")[1])
                fs.unlink(path_img, (err) => {
                    if (err) return console.log(err)
                    resolve(true)
                })
            }else resolve(true)

        })
    })
    //删除视频
    const  delete_videos = await new Promise( (resolve, reject) => {
        db.query("select * from videos where username = ?", request.user.username, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length > 0) {
                const urls = result.map(item => item.url.split("8080/")[1])
                result.forEach( item => {
                    db.query("delete from comments where video_id = ?", item.id, (err, result) => {
                        if (err) return console.log(err.message)
                    })
                })

                urls.forEach( item => { //path.join(__dirname, "../../", item)
                    fs.unlink(path.join(__dirname, "../../", item), (err) => {
                        if (err) return console.log(err.message)
                    })
                })
                resolve(true)
            }
            else resolve(true)
        })
    })

    //删除账号以及视频数据
    const delete_tables = await new Promise( (resolve, reject) => {
        db.query("DELETE FROM users WHERE id = ?", uid, (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) {
                db.query("delete from videos where username = ?", request.user.username, (err, result) => {
                    if (err) return console.log(err.message)
                    resolve(true)
                })

            }
        })
    })
    if (delete_img && delete_videos && delete_tables) response.send({code: 200, message: "注销账号成功"})
    else response.send({code: 200, message: "注销账号失败"})

})


//获取用户的稿件
router.get("/get_manuscript", (request, response) => {
    db.query("select * from videos where username = ?", request.user.username, (err, result) => {
        if (err) return console.log(err.message)
        response.send({ code: 200, message: "查询成功", data: result})
    })
})



//用户删除稿件
router.get("/delete_video", async (request, response) => {
    const { id, url } = request.query
    const delete_flag = await new Promise( (resolve, reject) => {
        fs.unlink(path.join(__dirname, "../../", url.split("8080/")[1]), (err) => {
            if (err) return console.log(err.message)
            resolve(true)
        })
    })
    if (delete_flag) {
        db.query("delete from videos where id = ?", id, (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) {
                db.query("delete from comments where video_id = ?", id, (err, result) => {
                    if (err) return console.log(err.message)
                    response.send({code: 200, message: "删除成功"})

                })
            }
        })
    }
})



//点赞和收藏
router.post("/likes_and_collection", async (request, response) => {
    const {data: {likes, collection, id}} = await new Promise( (resolve, reject) => {
        request.on("data", (data) => {
            resolve(JSON.parse(data.toString()))
        })
    })
    db.query("update users set likes = ?, collection = ? where  id = ?", [likes, collection, id], (err, result) => {
        if (err) return console.log(err.message)
        if (result.affectedRows === 1) response.send({code: 200, message: "修改成功"})
    })
})



//发表评论
router.post("/speak", async (request, response) => {
    const data = await new Promise((resolve, reject) => {
        request.on("data", (data) => {
            resolve(JSON.parse(data.toString()))
        })
    })
    db.query("insert into comments (content, username, user_pic, time, video_id) values (?,?,?,?,?)", [data.speak, request.user.username, request.user.pic, getTime(), data.video_id], (err, result) => {
    if (err) return console.log(err.message)
    if (result.affectedRows === 1) return response.send({code: 200, message: "评论成功"})
        })
})


//删除视频评论
router.get("/delete_comment", (request, response) => {
    db.query("delete from comments where id = ?", request.query.id, (err, result) => {
        if (err) return console.log(err.message)
        if (result.affectedRows === 1) return response.send({code: 200, message: "删除评论成功"})
    })
})

//修改video表里的collections_count
router.get("/update_collection", async (request, response) => {
    const collection = await new Promise((resolve, reject) => {
        db.query("select * from videos where id = ?", request.query.video_id, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length === 1) resolve(result[0].collection)
        })
    })
    if (request.query.flag === "true") {
        console.log("@@@@@@")
        db.query("update videos set collection = ? where id = ?", [collection + 1,  parseInt(request.query.video_id)], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) response.send({code: 200, message: "修改成功"})
        })
    }
    else {
        db.query("update videos set collection = ? where id = ?", [(collection - 1) < 0 ? 0 : collection - 1,  parseInt(request.query.video_id)], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) response.send({code: 200, message: "修改成功"})
        })
    }
})

//修改video表里的like_count
router.get("/update_like_count", async (request, response) =>  {
    const {flag,video_id} = request.query
    const like_count = await new Promise( (resolve, reject) => {
        db.query("select * from videos where id = ?", video_id, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length === 1) resolve(result[0].like_count)
        })
    })
    if (flag === "true") {
        db.query("update videos set like_count = ? where id = ?", [like_count + 1, video_id], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) response.send({code: 200, message: "修改成功"})
        })
    }
    else {
        db.query("update videos set like_count = ? where id = ?", [(like_count - 1) < 0 ? 0: like_count - 1, video_id], (err, result) => {
            if (err) return console.log(err.message)
            if (result.affectedRows === 1) response.send({code: 200, message: "修改成功"})
        })
    }
})

//点击关注
router.get("/concern", (request, response) => {
    db.query("update users set concern = ? where id = ?", [request.query.current, request.user.id], (err, result) => {
        if (err) return console.log(err.message)
        if (result.affectedRows === 1) return response.send("hello")
    })
})

//获取当前用户的关注列表
router.get("/get_concern_list", async (request, response) => {
    const array = await new Promise( (resolve, reject) => {
        db.query("select concern from users where id = ?", request.user.id, (err, result) => {
            if (err) return console.log(err.message)
            else resolve(JSON.parse(result[0].concern))
        })
    })
    db.query(`select * from users where id in (${array.join(", ")})`, (err, result) => {
        if (err) return console.log(err.message)
        else return response.send({code: 200, message: "获取成功", data: result})
    })
})
//获取当前时间
function getTime() {
    const time = new Date()
    const year = time.getFullYear()
    const month = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1
    const day = time.getDate() + 1 < 10 ? "0" + time.getDate() : time.getDate()
    const hours = time.getHours() + 1 < 10 ? "0" + time.getHours() : time.getHours()
    const minutes = time.getMinutes() + 1 < 10 ? "0" + time.getMinutes() : time.getMinutes()
    const seconds = time.getSeconds() + 1 < 10 ? "0" + time.getSeconds() : time.getSeconds()
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
module.exports = router